<form class="upload-form">
    <div class="control-group">
        <textarea
            bind:value="chartData"
            readonly="{readonly}"
            id="upload-data-text"
            style="resize: none"
            placeholder="{placeholder}"
        ></textarea>
    </div>
</form>

<script>
    /* globals dw */
    import httpReq from '@datawrapper/shared/httpReq';
    import { throttle } from 'underscore';
    import { __ } from '@datawrapper/shared/l10n';

    let app;
    const chart = dw.backend.currentChart;

    const updateData = throttle(() => {
        const { chartData } = app.get();
        httpReq.put(`/v3/charts/${chart.get('id')}/data`, {
            body: chartData,
            headers: {
                'Content-Type': 'text/csv'
            }
        });
    }, 1000);

    export default {
        data() {
            return {
                placeholder: __('upload / paste here')
            };
        },
        oncreate() {
            app = this;
        },
        // eslint-disable-next-line
        onupdate({ changed, current, previous }) {
            if (
                changed.chartData &&
                current.chartData &&
                previous &&
                previous.chartData !== current.chartData
            ) {
                updateData();
            }
        }
    };
</script>

<style>
    textarea#upload-data-text {
        height: 260px;
    }
</style>
